<?php
namespace app\api\controller\xcx;

use app\BaseController;
use app\common\utils\Curl;
use app\common\utils\Res;
use Exception;
use think\facade\Db;

class Things extends BaseController
{
    //插入每天吃的什么
    public function insertData()
    {
        $param = $this->request->post();
        
        //获取登录用户ID
        $param['uid'] = 1;//$this->request->id;
        
        //验证数据
        if (!isset($param['thing']) || empty($param['thing'])) {
            return Res::error('请输入你想吃的东西！');
        }
        if (!isset($param['price']) || empty($param['price'])) {
            return Res::error('请输入价格！');
        }
        if (!isset($param['type']) || empty($param['type'])) {
            return Res::error('请输入吃的类型！');
        }
        
        $param['create_time'] = date('Y-m-d H:i:s',time());
        $param['date'] = date('Y-m-d',time());

        try {
            
            Db::startTrans();
            Db::table('eat_info')->insert($param);
            Db::commit();  // 提交事务
            return Res::ok('Add successfully');
        } catch (Exception $e) {
            Db::rollBack();  // 回滚事务
            return Res::error('添加失败:' . $e->getMessage());
        }
    }
    
    //随机获取范围3公里的美食（根据腾讯地图）
    public function getFood()
    {
        $param = $this->request->post();

        $key = env('Tencent.Foodmap'); // 替换为你的腾讯地图key
        $location = $param['lat'] . ',' . $param['lng'];//'30.20098706063609,120.22132414725377'; // 用户位置坐标, 格式：纬度,经度
        $radius = 3000; // 搜索半径，单位为米，这里设置为3公里
        $keyword = '美食'; // 搜索关键字
        $page_index = $param['page_index'];

        // 构建API请求URL
        $url = "https://apis.map.qq.com/ws/place/v1/search?keyword={$keyword}&boundary=nearby({$location},{$radius})&page_size=20&page_index={$page_index}&output=json&key={$key}";

        $data = Curl::callWebServer($url);
        
        // 检查API是否返回错误
        if ($data['status'] == 0) {
            // API调用成功，处理数据
            $results = $data['data'];
            // 遍历结果并打印
            $d = [];
            foreach ($results as $k => $result) {
                $d[$k]['title'] = $result['title'];
                $d[$k]['address'] = $result['address'];
                $d[$k]['category'] = $result['category'];
                $d[$k]['_distance'] = $result['_distance'] . '米';
            }
            // 获取随机键
            $randomKey = array_rand($d);

            // 获取随机值
            $randomValue = $d[$randomKey];
        } else {
            // 处理错误情况
            return Res::error("查询失败，错误码：{$data['status']}，错误信息：{$data['message']}");
        }

        return Res::ok($randomValue);
    }
    
    //随机吃过的菜
    public function getLocation()
    {
        $uid = 1;//$this->request->id;
        $data = Db::table('eat_info')->where('uid',$uid)->select()->toArray();
        // 获取随机键
        $randomKey = array_rand($data);
        // 获取随机值
        $randomValue = $data[$randomKey];
        
        $result = [
            'id' => $randomValue['id'],
            'title' => $randomValue['thing']
        ];

        return Res::ok($result);
    }
    
    public function getRound()
    {
        $data = [2,3,4,7,8];
        // 获取随机键
        $randomKey = array_rand($data);
        // 获取随机值
        $randomValue = $data[$randomKey];
        return Res::ok($randomValue);
    }
    
}
